import simplejson as json
import os, sys, tempfile, zipfile
from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
from sprite import *

class SpriteFile(QObject):
    def __init__(self, sprite):
        QObject.__init__(self)
        self.sprite = sprite

    def save_gif(self, savefile, flattened = False):
        if not str(savefile).endswith(".gif"):
            savefile = savefile + ".gif"

        sequence = []

        for frame_index,frame in enumerate(self.sprite.frames):
            imagefile = frame.get_pixmap(True).toImage()

            imagetmp = QTemporaryFile()
            imagetmp.setAutoRemove(False)
            imagefile.save(imagetmp, "png", 100)

            sequence.append(str(imagetmp.fileName()))

            imagetmp.close()

        # FIXME
        command = "/opt/local/bin/convert -delay 0 -loop 0 " + ' '.join(sequence) + " " + savefile
        os.system(str(command))

        print "Wrote Animated GIF:", savefile
        
    def save(self, savefile, flattened = False):
        if not str(savefile).endswith(".bsz"):
            savefile = savefile + ".bsz"
            
        zip = zipfile.ZipFile(str(savefile), "w")
        data = self.sprite.todict()
        
        # make temp directory
        # build json
        jsontmp = tempfile.NamedTemporaryFile()
        json.dump(data, jsontmp)
        jsontmp.flush()
        zip.write(jsontmp.name,"brs.json")
        
        # build images

        imagefiles = {}
        
        for frame_index,frame in enumerate(self.sprite.frames):
            for layer_index, layer in enumerate(frame.layers):
                a = QColor(0,0,0)
                b = QColor(255,0,255)
                frame.color_swap(layer_index, a, b)

        for frame_index,frame in enumerate(self.sprite.frames):
            if not flattened:
                for layer in frame.layers:
                    layer_index = frame.layers.index(layer)
                    image_filename = "images/image_%d_%d.png" % (frame_index, layer_index)
                    imagefiles[image_filename] = layer.toImage()

            image_filename = "images/flattened_%d.png" % (frame_index)

            pm = frame.get_pixmap()

            imagefiles[image_filename] = pm.toImage()

        """
        I'm sure reverting or avoiding this with copies
        would be a better way, but I'm not up for it.
        """
        for frame_index,frame in enumerate(self.sprite.frames):
            for layer_index, layer in enumerate(frame.layers):
                a = QColor(255,0,255)
                b = QColor(0,0,0)
                frame.color_swap(layer_index, a, b)

        # iterate, erate, erate, erate!
        for image_filename, imagefile in imagefiles.iteritems():
            imagetmp = QTemporaryFile()
            imagetmp.setAutoRemove(False)
            imagefile.save(imagetmp, "png", -1)
            zip.write(imagetmp.fileName(), image_filename)
            imagetmp.close()

        print "flattened:",flattened
        print zip.printdir()
        
        zip.close()
        
        return savefile
        
    def load(self, loadfile):
        zip = zipfile.ZipFile(str(loadfile), "r") 
        
        images = {}
        namelist = zip.namelist()
        for name in namelist:
            if name.startswith("images/"):
                images[name] = QImage()
                images[name].loadFromData(zip.read(name))
                
        j = zip.read("brs.json")
        
        s = Sprite.fromjson(j, images)
        
        return s
